import { Component, OnInit } from '@angular/core';
import { JsonApiService } from "app/core/api/json-api.service"; //http请求配置引入
import { Router, ActivatedRoute } from "@angular/router"; //路由引入
import { config } from '../../shared/smartadmin.config';
declare var $: any;
@Component({
	selector: 'sa-company',
	templateUrl: './kafka-push-config.component.html',
	styleUrls: ['./kafka-push-config.component.css']
})
export class KafkaPushConfigComponent implements OnInit {
	tableData: any = []; //table数据
	totalCount: number = 0; //分页总条数
	curPage: number = 1; //分页当前页
	pageSize: number = 10; //内置的分页每页条数
	searchKey: string = ''; //搜索keyword
	startTime: string = '';
	endTime: string = '';
	initDateRange: any = {
		startTime: '',
		endTime: '',
	}// 时间组件需要渲染的值
	carNumber: string = ''
	deviceId: string = ''
	topic: string = ''

	topicForm: any = {
		deviceId: '',
		topics: '',
		remark: ''
	}
	topicRoleForm: any = {
		roleId: null,
		topic: '',
		remark: ''
	}

	paramFormat:any = {
        id:'id',
        text:'name',
    }
	dataURL:string = "role/roleList.html"
	fileUp: string = ''
	fileToUpload: File = null; //上传文件回调参数
	roleList: any = []

	constructor(private jsonApiService: JsonApiService, private router: Router, private activatedRoute: ActivatedRoute) {
		activatedRoute.queryParams.subscribe(queryParams => {
			this.curPage = queryParams.nowPage || 1;
		});
	}

	ngOnInit() {
		this.load();
		const that = this
		this.initAllRole().then(() => {
			that.select2Role().then(() => {
				$('#roleSelect2').val('').change()
				var str = $("<span class='select2-selection__rendered'></span>")
				$('#select2-roleSelect2-container').empty()
				$('#select2-roleSelect2-container').attr('title', '')
				$('#select2-roleSelect2-container').prepend(str)
			  })
		  })
		
		System.import('script-loader!select2/dist/js/select2.min.js').then(() => {
			System.import('assets/js/select2-zh-CN.js').then(() => {
				that.initCarNumbel();
			})
		});
		
	}
	// 接收子组件传递过来的数据 
	getSelectTableTime(time) {
		this.startTime = time.startTime;
		this.endTime = time.endTime;
	}
	//table刷新
	refresh() {
		this.load();
	}
	//表格搜索
	table_search(word) {
		this.curPage = 1
		this.searchKey = common.stringTrim(this.searchKey);
		this.load();
	}
	//初始化加载list数据
	load() {
		// if (!this.deviceId) {
		// 	this.jsonApiService.message('请选择车牌号')
		// 	return
		// }
		const params: any = {}
		if (this.searchKey) {
			params.searchKey = this.searchKey
		}
		params.deviceId = this.deviceId
		if (this.topic) {
			params.topics = this.topic
		}
		let data = {
			pageSize: this.pageSize,
			nowPage: this.curPage,
			parameters: params,
			isExport: false
		}
		let reqdata = 'gridPager=' + JSON.stringify(data);
		this.jsonApiService.http("kafkaconf/getKafkaConfList.html", reqdata).subscribe(data => {
			this.tableData = data.exhibitDatas;
			this.totalCount = data.recordCount;
		})
	}
	//导出
	exprotData() {
		if (this.startTime && !this.endTime) {
			this.jsonApiService.message('请选择结束时间');
			return
		}
		if (!this.startTime && this.endTime) {
			this.jsonApiService.message('请选择开始时间');
			return
		}
		let data = {
			pageSize: this.pageSize,
			nowPage: this.curPage,
			parameters: {
				searchName: this.searchKey,
				startTime: this.startTime,
				endTime: this.endTime,
			},
			isExport: true
		}
		common.exprotDataFile(data, 'gridPager', config.BaseURL + 'company/list.html')
	}
	//分页回调
	paginate(e) {
		this.curPage = e.page + 1;
		this.pageSize = e.rows;
		this.load();
	}
	//新建公司
	new_company() {
		this.router.navigate(['/system/company/company-page'], { queryParams: { type: 'new' } });
	}
	//编辑页面
	updata_company(row) {
		this.router.navigate(['/system/company/company-page'], { queryParams: { id: row.id, type: 'updata', nowPage: this.curPage } });
	}
	//公司删除
	del_row(row) {
		this.jsonApiService.confirm_message("此操作将永久删除数据,确认要删除?").then(() => {
			let reqdata = 'id=' + row.id;
			this.jsonApiService.http("kafkaconf/deleteKafkaConf.html", reqdata).subscribe(data => {
				this.jsonApiService.message(data.message);
				if (data.success) {
					this.load();
				}
			})
		})
	}
	//根据公司行业类型id获取行业类型中文
	getBusinessTypeText(businessType) {
		const item = businessTypeList.find(item => {
			return item.value === businessType
		})
		return item ? item.label : '--'
	}

//初始化车辆
initCarNumbel() {
	var that = this;
	$("#carNumberSelect").select2({
		language: "zh-CN",
		minimumInputLength: 2,
		allowClear: true,
		placeholder: "请选择",
		ajax: {
			url: config.BaseURL + "stats/carListByCarNumber.html",
			dataType: 'json',
			delay: 50,
			method: "POST",
			xhrFields: { withCredentials: true },
			data: function (params) { return { "carNumber": params.term }; },
			processResults: function (data, params) {
				var options = new Array();
				// 小于10个数量才判断重复
				if (data.data.length <= 10) {
					let arr = []
					let sameCar = []
					// 判断相同的车牌号
					for (let index = 0; index < data.data.length; index++) {
						let car = data.data[index];
						if (arr.indexOf(car.carNumber) != -1) {
							sameCar.push(car.carNumber)
						} else {
							arr.push(car.carNumber);
						}
					}
					$(data.data).each(function (index, car) {
						if (sameCar.indexOf(car.carNumber) != -1) {
							options.push({
								id: car.deviceId,
								text: car.carNumber + "[" + car.parentName + "]"
							})
						} else {
							options.push({
								id: car.deviceId,
								text: car.carNumber
							})
						}
					});
				} else {
					$(data.data).each(function (index, car) {
						options.push({
							id: car.deviceId,
							text: car.carNumber
						})
					});
				}
				return {
					results: options //获取查询后的结果
				};
			},
			cache: true
		},
		templateResult: function (state) {
			if (!state.id) { return state.text; }
			var $state = $('<span><i class="fa fa-car green"></i>&nbsp;&nbsp;' + state.text + '</span>');
			return $state;
		},
	}).on("select2:select", function (e) {
		var data = e.params.data;
		that.deviceId = data.id;
		if (data.text.indexOf('[') > 0) {
			that.carNumber = data.text.split('[')[0];
		} else {
			that.carNumber = data.text;
		}
	});

}
//清除车辆选中值
del_carNumber() {
	this.deviceId = '';
	this.carNumber = '';
	var str = $("<span class='select2-selection__placeholder'>请选择</span>");
	$('#carNumberSelect').val("");
	$("#select2-carNumberSelect-container").empty();
	$("#select2-carNumberSelect-container").attr("title", "");
	$("#select2-carNumberSelect-container").prepend(str);
}

validatorTopicOptions = {
    excluded: [':disabled'],
    feedbackIcons: {
      valid: 'glyphicon glyphicon-ok',
      invalid: 'glyphicon glyphicon-remove',
      validating: 'glyphicon glyphicon-refresh'
    },
    fields: {
		deviceId: {
			trigger: 'change',
        validators: {
          notEmpty: {
            message: '请选择车牌号码'
          }
        }
      },
      topics: {
        validators: {
          notEmpty: {
            message: '请输入topic'
          }
        }
      }
    }
  }


	openTopicModal(modal) {
		const that = this
		this.topicForm = {
			deviceId: '',
			topics: '',
			remark: ''
		}
		$('#topicFormBox').data('bootstrapValidator').resetForm()
		this.del_carNumber2()
		System.import('script-loader!select2/dist/js/select2.min.js').then(() => {
			System.import('assets/js/select2-zh-CN.js').then(() => {
				that.initCarNumbel2();
			})
		});
		modal.show()
	}
	// topic弹窗关闭
	closeTopicModal(modal) {
		$('#topicFormBox').data('bootstrapValidator').resetForm()
		modal.hide()
	}

	topicSubmit(modal) {
		$('#topicFormBox').bootstrapValidator('validate') //开启验证
		let isValid = $('#topicFormBox').data('bootstrapValidator').isValid() //验证是否通过
		if (isValid) {
			let url = 'kafkaconf/saveOrUpdate.html'
			this.jsonApiService.http_obj(url, this.topicForm).subscribe(data => {
				this.jsonApiService.message(data.message);
				if (data.success) {
					this.load();
					modal.hide();
				}
			})
		}
	}

	//清除新弹窗车辆选中值
del_carNumber2() {
	this.topicForm.carNumber = '';
	this.topicForm.deviceId = '';
	var str = $("<span class='select2-selection__placeholder'>请选择</span>");
	$('#carNumberSelectAdd').val("");
	$("#select2-carNumberSelectAdd-container").empty();
	$("#select2-carNumberSelectAdd-container").attr("title", "");
	$("#select2-carNumberSelectAdd-container").prepend(str);
}

//初始化车辆
initCarNumbel2() {
	var that = this;
	$("#carNumberSelectAdd").select2({
		language: "zh-CN",
		minimumInputLength: 2,
		allowClear: true,
		placeholder: "请选择",
		ajax: {
			url: config.BaseURL + "stats/carListByCarNumber.html",
			dataType: 'json',
			delay: 50,
			method: "POST",
			xhrFields: { withCredentials: true },
			data: function (params) { return { "carNumber": params.term }; },
			processResults: function (data, params) {
				var options = new Array();
				// 小于10个数量才判断重复
				if (data.data.length <= 10) {
					let arr = []
					let sameCar = []
					// 判断相同的车牌号
					for (let index = 0; index < data.data.length; index++) {
						let car = data.data[index];
						if (arr.indexOf(car.carNumber) != -1) {
							sameCar.push(car.carNumber)
						} else {
							arr.push(car.carNumber);
						}
					}
					$(data.data).each(function (index, car) {
						if (sameCar.indexOf(car.carNumber) != -1) {
							options.push({
								id: car.deviceId,
								text: car.carNumber + "[" + car.parentName + "]"
							})
						} else {
							options.push({
								id: car.deviceId,
								text: car.carNumber
							})
						}
					});
				} else {
					$(data.data).each(function (index, car) {
						options.push({
							id: car.deviceId,
							text: car.carNumber
						})
					});
				}
				return {
					results: options //获取查询后的结果
				};
			},
			cache: true
		},
		templateResult: function (state) {
			if (!state.id) { return state.text; }
			var $state = $('<span><i class="fa fa-car green"></i>&nbsp;&nbsp;' + state.text + '</span>');
			return $state;
		},
	}).on("select2:select", function (e) {
		var data = e.params.data;
		that.topicForm.deviceId = data.id;
	});

}

validatorRoleOptions = {
    excluded: [':disabled'],
    feedbackIcons: {
      valid: 'glyphicon glyphicon-ok',
      invalid: 'glyphicon glyphicon-remove',
      validating: 'glyphicon glyphicon-refresh'
    },
    fields: {
		roleId: {
			trigger: 'change',
        validators: {
          notEmpty: {
            message: '请选择角色'
          }
        }
      },
      topics: {
        validators: {
          notEmpty: {
            message: '请输入topic'
          }
        }
      }
    }
  }

// 一下是批量新增角色的
openTopicRoleModal(modal) {
	const that = this
	this.topicRoleForm = {
		roleId: null,
		topic: '',
		remark: ''
	}
	$('#topicRoleFormBox').data('bootstrapValidator').resetForm()
	var str=$("<span class='select2-selection__placeholder'>请选择</span>");
	$('#roleSelect2').val("");
	$("#select2-roleSelect2-container").empty();
	$("#select2-roleSelect2-container").attr("title","");
	$("#select2-roleSelect2-container").prepend(str);
	modal.show()
}
	// topic弹窗关闭
	closeTopicRoleModal(modal) {
		$('#topicRoleFormBox').data('bootstrapValidator').resetForm()
		modal.hide()
	}

	 //角色选中
	 optionSelected(data){
        this.topicRoleForm.roleId = data.id;
    }

	topicRoleSubmit(modal) {
		$('#topicRoleFormBox').bootstrapValidator('validate') //开启验证
		let isValid = $('#topicRoleFormBox').data('bootstrapValidator').isValid() //验证是否通过
		if (isValid) {
			let url = 'kafkaconf/addByRoleId.html'
			this.jsonApiService.http_obj(url, this.topicRoleForm).subscribe(data => {
				this.jsonApiService.message(data.message);
				if (data.success) {
					this.load();
					modal.hide();
				}
			})
		}
	}

	  // 显示导入的弹框
	  showImportModal(modal) {
		modal.show()
	  }
	  // 关闭导入的弹框
	  cancelUp(val) {
		val.hide()
		this.fileToUpload = null
	  }
	  //下载模板
	  load_module() {
		var elemIF = document.createElement('iframe')
		elemIF.src = config.BaseURL + 'resources/template/Kafka-Config-Teamplate.xlsx'
		elemIF.style.display = 'none'
		document.body.appendChild(elemIF)
	  }
	  // 清空input type=file输入框的值
	  clearFile() {
		this.fileUp = ''
	  }
	
	  //文件上传change回调
	  fileChange(files) {
		console.log(files)
		// 这一层循环判断格式是否正确
		this.fileToUpload = files.item(0);
		const isEXCEL = this.fileToUpload.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || this.fileToUpload.type === "application/vnd.ms-excel";
		if (!isEXCEL) {
			this.jsonApiService.message('上传文件只能是 excel格式!');
			this.fileToUpload = null;
			return;
		}
	  }
	
	  //导入submit
	  submitData(val) {
		let postParam = new FormData();
		postParam.append('file', this.fileToUpload);
		if (!this.fileToUpload) {
			this.jsonApiService.message('请上传文件')
			return false;
		}
		this.jsonApiService.form_http("kafkaconf/fileUpload.html", postParam).subscribe(data => {
			this.jsonApiService.message(data.message);
			if (data.success) {
				val.hide();
				this.fileToUpload = null;
				this.load();
			}
		})
	  }

	  delhwTopic() {
		this.topic = ''
	  }

	  //拉取角色数据
  initAllRole() {
    var that = this
    //修改为展示所有角色的数据
    let reqdata = 'userType=1'
    return new Promise(function (resolve, reject) {
      that.jsonApiService.http('role/roleList.html', reqdata).subscribe(data => {
        if (data.success) {
          var roleList = data.data
          var selectdata = []
          for (var i = 0; i < roleList.length; i++) {
            var obj = {
              id: roleList[i].id,
              text: roleList[i].name
            }
            selectdata[i] = obj
          }
          that.roleList = selectdata
          resolve()
        } else {
          this.jsonApiService.message(data.message)
          reject()
        }
      })
    })
  }

	    //初始化select2 角色配置
  select2Role() {
    var that = this
    return new Promise(function (resolve, reject) {
      System.import('script-loader!select2/dist/js/select2.min.js').then(() => {
        System.import('assets/js/select2-zh-CN.js').then(() => {
			$('#roleSelect2')
            .select2({
              language: 'zh-CN',
              placeholder: '请选择',
              allowClear: true,
              data: that.roleList //为Select添加数据
            })
            .on('select2:select', function (e) {
              var data = e.params.data
              $('#roleSelect2').val(data.id).change()
              that.topicRoleForm.roleId = data.id
            //   that.topicRoleForm.roleName = data.text
            })
          resolve()
        })
      })
    })
  }
}